package com.zkca.xf.ui.activity.nfc.lochy;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothDevice;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


import com.google.gson.Gson;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zkca.xf.Constants_SP;
import com.zkca.xf.MyApplication;
import com.zkca.xf.R;
import com.zkca.xf.base.BaseTitleActivity;
import com.zkca.xf.model.javabean.FaultJobLBean;
import com.zkca.xf.model.javabean.JobLBean;
import com.zkca.xf.model.javabean.uploadbean.RequestInspect;
import com.zkca.xf.presenter.JobLPresenter;
import com.zkca.xf.ui.activity.nfc.bleNfc.BleManager.BleManager;
import com.zkca.xf.ui.activity.nfc.bleNfc.BleManager.Scanner;
import com.zkca.xf.ui.activity.nfc.bleNfc.BleManager.ScannerCallback;
import com.zkca.xf.ui.activity.nfc.bleNfc.BleNfcDeviceService;
import com.zkca.xf.ui.activity.nfc.bleNfc.DeviceManager.BleNfcDevice;
import com.zkca.xf.ui.activity.nfc.bleNfc.DeviceManager.ComByteManager;
import com.zkca.xf.ui.activity.nfc.bleNfc.DeviceManager.DeviceManager;
import com.zkca.xf.ui.activity.nfc.bleNfc.DeviceManager.DeviceManagerCallback;
import com.zkca.xf.ui.activity.nfc.bleNfc.Exception.CardNoResponseException;
import com.zkca.xf.ui.activity.nfc.bleNfc.Exception.DeviceNoResponseException;
import com.zkca.xf.ui.activity.nfc.bleNfc.Tool.StringTool;
import com.zkca.xf.ui.activity.nfc.bleNfc.card.CpuCard;
import com.zkca.xf.ui.activity.nfc.bleNfc.card.FeliCa;
import com.zkca.xf.ui.activity.nfc.bleNfc.card.Iso14443bCard;
import com.zkca.xf.ui.activity.nfc.bleNfc.card.Iso15693Card;
import com.zkca.xf.ui.activity.nfc.bleNfc.card.Mifare;
import com.zkca.xf.ui.activity.nfc.bleNfc.card.Ntag21x;
import com.zkca.xf.ui.activity.personprotect.Device_XActivity;
import com.zkca.xf.ui.activity.personprotect.DeviceaddAct;
import com.zkca.xf.ui.activity.personprotect.FaultJobSubmitActivity;
import com.zkca.xf.ui.activity.personprotect.FaultJob_LActivity;
import com.zkca.xf.ui.activity.personprotect.JobCheckActivity;
import com.zkca.xf.ui.activity.personprotect.Job_LActivity;
import com.zkca.xf.utils.LogUtil;
import com.zkca.xf.utils.SPUtil;
import com.zkca.xf.utils.TimeUtils;
import com.zkca.xf.utils.ToastUtils;
import com.zkca.xf.view.JobLView;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import io.reactivex.functions.Consumer;
import okhttp3.Call;

public class MainbActivity extends BaseTitleActivity implements JobLView {
    BleNfcDeviceService mBleNfcDeviceService;
    private BleNfcDevice bleNfcDevice;
    private Scanner mScanner;
    private Button searchButton = null;
    private EditText msgText = null;
    private ProgressDialog readWriteDialog = null;
    private AlertDialog.Builder alertDialog = null;

    private StringBuffer msgBuffer;
    private BluetoothDevice mNearestBle = null;
    private Lock mNearestBleLock = new ReentrantLock();// 锁对象
    private int lastRssi = -100;
    private CharSequence[] items = null;
//    private String pollingId_;
//    private String shangye, id_old, pollingId, form;
//    private String id,neirong,shebeiMingcheng;
//    private String dijige,id2;
    private Intent intent2;
    private String shangye;
    String[] permissions = {Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION};

    private RequestInspect requestInspect;
    private JobLPresenter jobLPresenter;
    private int taskId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mainb);
        setTitleText("贴一贴");

        intent2=getIntent();
        shangye = intent2.getStringExtra("TAG");
        jobLPresenter = new JobLPresenter(this, this);

//        Intent intent = getIntent();
//        shangye = intent.getStringExtra("shangye");
//        if ("device".equals(shangye)) {
//            id_old = intent.getStringExtra("ID");
//            pollingId_ = intent.getStringExtra("pollingId");
//            if (intent.hasExtra("neirong")){
//                neirong=intent.getStringExtra("neirong");
//                shebeiMingcheng=intent.getStringExtra("shebeiMingcheng");
//            }
//            String[] split = pollingId_.split("#");
//            pollingId = split[0];
//            form = split[1];
//
//        }else if ("xunjianJob".equals(shangye)){
//            dijige= intent.getStringExtra("dijige");
//            Log.e("lishuai1234",dijige);
//        }

        msgBuffer = new StringBuffer();

        searchButton = (Button) findViewById(R.id.searchButton);
        Button sendButton = (Button) findViewById(R.id.sendButton);
        Button changeBleNameButton = (Button) findViewById(R.id.changeBleNameButton);
        msgText = (EditText) findViewById(R.id.msgText);
        Button clearButton = (Button) findViewById(R.id.clearButton);
        Button openBeepButton = (Button) findViewById(R.id.openBeepButton);
        Button closeBeepButton = (Button) findViewById(R.id.closeBeepButton);
        Button openAntiLostButton = (Button) findViewById(R.id.openAntiLostButton);
        Button closeAntiLostButton = (Button) findViewById(R.id.closeAntiLostButton);
        Button openAutoSearchCard = (Button) findViewById(R.id.openAutoSearchCard);
        Button closeAutoSearchCard = (Button) findViewById(R.id.closeAutoSearchCard);

        readWriteDialog = new ProgressDialog(MainbActivity.this);
        readWriteDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        // 设置ProgressDialog 标题
        readWriteDialog.setTitle("请稍等");
        // 设置ProgressDialog 提示信息
        readWriteDialog.setMessage("正在读写数据……");
        // 设置ProgressDialog 标题图标
        readWriteDialog.setIcon(R.mipmap.ic_launcher);

        clearButton.setOnClickListener(new claerButtonListener());
        searchButton.setOnClickListener(new StartSearchButtonListener());
        sendButton.setOnClickListener(new SendButtonListener());
        changeBleNameButton.setOnClickListener(new changeBleNameButtonListener());
        openBeepButton.setOnClickListener(new OpenBeepButtonListener());
        closeBeepButton.setOnClickListener(new closeBeepButtonListener());
        openAntiLostButton.setOnClickListener(new OpenAntiLostButtonListener());
        closeAntiLostButton.setOnClickListener(new CloseAntiLostButtonListener());
        openAutoSearchCard.setOnClickListener(new OpenAutoSearchCardButtonListener());
        closeAutoSearchCard.setOnClickListener(new CloseAutoSearchCardButtonListener());

        //ble_nfc服务初始化
        Intent gattServiceIntent = new Intent(this, BleNfcDeviceService.class);
        bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);

        msgText.setText("BLE_NFC Demo v2.0.0 20170410");
    }

    // Code to manage Service lifecycle.
    private final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            BleNfcDeviceService mBleNfcDeviceService = ((BleNfcDeviceService.LocalBinder) service).getService();
            bleNfcDevice = mBleNfcDeviceService.bleNfcDevice;
            mScanner = mBleNfcDeviceService.scanner;
            mBleNfcDeviceService.setDeviceManagerCallback(deviceManagerCallback);
            mBleNfcDeviceService.setScannerCallback(scannerCallback);

            //开始搜索设备
            RxPermissions rxPermissions = new RxPermissions(MainbActivity.this);
            rxPermissions.request(permissions)
                    .subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(@NonNull Boolean granted) throws Exception {
                            //同意授权
                            if (granted) {
                                if (ActivityCompat.checkSelfPermission(MainbActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                                    ToastUtils.show(MainbActivity.this, "请添加权限");
                                    return;
                                }
                                searchNearestBleDevice();
                            } else {//拒绝
                                ToastUtils.show(MainbActivity.this, "请添加权限");
                            }
                        }
                    });

        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBleNfcDeviceService = null;
        }
    };



    @Override
    public void onResume() {
        super.onResume();
        if (mBleNfcDeviceService != null) {
            mBleNfcDeviceService.setScannerCallback(scannerCallback);
            mBleNfcDeviceService.setDeviceManagerCallback(deviceManagerCallback);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbindService(mServiceConnection);
    }

    //Scanner 回调
    private ScannerCallback scannerCallback = new ScannerCallback() {
        @Override
        public void onReceiveScanDevice(BluetoothDevice device, int rssi, byte[] scanRecord) {
            super.onReceiveScanDevice(device, rssi, scanRecord);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //StringTool.byteHexToSting(scanRecord.getBytes())
                System.out.println("Activity搜到设备：" + device.getName()
                        + " 信号强度：" + rssi
                        + " scanRecord：" + StringTool.byteHexToSting(scanRecord));
            }
            //搜索蓝牙设备并记录信号强度最强的设备
            if ((scanRecord != null) && (StringTool.byteHexToSting(scanRecord).contains("017f5450"))) {  //从广播数据中过滤掉其它蓝牙设备
                msgBuffer.append("搜到设备：").append(device.getName()).append(" 信号强度：").append(rssi).append("\r\n");
                handler.sendEmptyMessage(0);
                if (mNearestBle != null) {
                    if (rssi > lastRssi) {
                        mNearestBleLock.lock();
                        try {
                            mNearestBle = device;
                        } finally {
                            mNearestBleLock.unlock();
                        }
                    }
                } else {
                    mNearestBleLock.lock();
                    try {
                        mNearestBle = device;
                    } finally {
                        mNearestBleLock.unlock();
                    }
                    lastRssi = rssi;
                }
            }
        }

        @Override
        public void onScanDeviceStopped() {
            super.onScanDeviceStopped();
        }
    };

    //设备操作类回调
    private DeviceManagerCallback deviceManagerCallback = new DeviceManagerCallback() {
        @Override
        public void onReceiveConnectBtDevice(boolean blnIsConnectSuc) {
            super.onReceiveConnectBtDevice(blnIsConnectSuc);
            if (blnIsConnectSuc) {
                System.out.println("Activity设备连接成功");
                msgBuffer.delete(0, msgBuffer.length());
                msgBuffer.append("设备连接成功!\r\n");
                if (mNearestBle != null) {
                    msgBuffer.append("设备名称：").append(bleNfcDevice.getDeviceName()).append("\r\n");
                }
                msgBuffer.append("信号强度：").append(lastRssi).append("dB\r\n");
                msgBuffer.append("SDK版本：" + BleNfcDevice.SDK_VERSIONS + "\r\n");

                //连接上后延时500ms后再开始发指令
                try {
                    Thread.sleep(500L);
                    handler.sendEmptyMessage(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onReceiveDisConnectDevice(boolean blnIsDisConnectDevice) {
            super.onReceiveDisConnectDevice(blnIsDisConnectDevice);
            System.out.println("Activity设备断开链接");
            msgBuffer.delete(0, msgBuffer.length());
            msgBuffer.append("设备断开链接!");
            handler.sendEmptyMessage(0);
        }

        @Override
        public void onReceiveConnectionStatus(boolean blnIsConnection) {
            super.onReceiveConnectionStatus(blnIsConnection);
            System.out.println("Activity设备链接状态回调");
        }

        @Override
        public void onReceiveInitCiphy(boolean blnIsInitSuc) {
            super.onReceiveInitCiphy(blnIsInitSuc);
        }

        @Override
        public void onReceiveDeviceAuth(byte[] authData) {
            super.onReceiveDeviceAuth(authData);
        }

        @Override
        //寻到卡片回调
        public void onReceiveRfnSearchCard(boolean blnIsSus, int cardType, byte[] bytCardSn, byte[] bytCarATS) {
            super.onReceiveRfnSearchCard(blnIsSus, cardType, bytCardSn, bytCarATS);
            if (!blnIsSus || cardType == BleNfcDevice.CARD_TYPE_NO_DEFINE) {
                return;
            }

            System.out.println("Activity接收到激活卡片回调：UID->" + StringTool.byteHexToSting(bytCardSn) + " ATS->" + StringTool.byteHexToSting(bytCarATS));

            final int cardTypeTemp = cardType;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    boolean isReadWriteCardSuc;
                    try {
                        if (bleNfcDevice.isAutoSearchCard()) {
                            //如果是自动寻卡的，寻到卡后，先关闭自动寻卡
                            bleNfcDevice.stoptAutoSearchCard();
                            isReadWriteCardSuc = readWriteCardDemo(cardTypeTemp);

                            //读卡结束，重新打开自动寻卡
                            startAutoSearchCard();
                        } else {
                            isReadWriteCardSuc = readWriteCardDemo(cardTypeTemp);

                            //如果不是自动寻卡，读卡结束,关闭天线
                            bleNfcDevice.closeRf();
                        }

                        //打开蜂鸣器提示读卡完成
                        if (isReadWriteCardSuc) {
                            bleNfcDevice.openBeep(50, 50, 3);  //读写卡成功快响3声
                        } else {
                            bleNfcDevice.openBeep(100, 100, 2); //读写卡失败慢响2声
                        }
                    } catch (DeviceNoResponseException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

        @Override
        public void onReceiveRfmSentApduCmd(byte[] bytApduRtnData) {
            super.onReceiveRfmSentApduCmd(bytApduRtnData);

            System.out.println("Activity接收到APDU回调：" + StringTool.byteHexToSting(bytApduRtnData));
        }

        @Override
        public void onReceiveRfmClose(boolean blnIsCloseSuc) {
            super.onReceiveRfmClose(blnIsCloseSuc);
        }

        @Override
        //按键返回回调
        public void onReceiveButtonEnter(byte keyValue) {
            if (keyValue == DeviceManager.BUTTON_VALUE_SHORT_ENTER) { //按键短按
                System.out.println("Activity接收到按键短按回调");
                msgBuffer.append("按键短按\r\n");
                handler.sendEmptyMessage(0);
            } else if (keyValue == DeviceManager.BUTTON_VALUE_LONG_ENTER) { //按键长按
                System.out.println("Activity接收到按键长按回调");
                msgBuffer.append("按键长按\r\n");
                handler.sendEmptyMessage(0);
            }
        }
    };

    @Override
    public void showProgressDialog() {

    }

    @Override
    public void hideProgressDialog() {

    }

    @Override
    public void showError(String msg) {

    }

    @Override
    public void getJobL(JobLBean jobLBean) {
        if (jobLBean.getResult() == 0) {
            List<JobLBean.DataBean> data = jobLBean.getData();
            int size = data.size();
            Intent intent=new Intent();
            if (size!=0) {
                intent.setClass(MainbActivity.this, JobCheckActivity.class);
                intent.putExtra("jobbean", data.get(0));
                startActivity(intent);
                finish();
            } else {
                ToastUtils.show(this, "该设备不是作业目标设备");
                intent.setClass(MainbActivity.this, Job_LActivity.class);
                intent.putExtra("taskId", taskId);
                startActivity(intent);
                finish();
            }
        }
    }

    //搜索按键监听
    private class StartSearchButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if ((bleNfcDevice.isConnection() == BleManager.STATE_CONNECTED)) {
                bleNfcDevice.requestDisConnectDevice();
                return;
            }
            RxPermissions rxPermissions = new RxPermissions(MainbActivity.this);
            rxPermissions.request(permissions)
                    .subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(@NonNull Boolean granted) throws Exception {
                            //同意授权
                            if (granted) {
                                if (ActivityCompat.checkSelfPermission(MainbActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                                    ToastUtils.show(MainbActivity.this, "请添加权限");
                                    return;
                                }
                                searchNearestBleDevice();
                            } else {//拒绝
                                ToastUtils.show(MainbActivity.this, "请添加权限");
                            }
                        }
                    });

//            if (!mScanner.isScanning() && (bleNfcDevice.isConnection() == BleManager.STATE_DISCONNECTED)) {
//                //开始搜索设备
//                msgBuffer.delete(0, msgBuffer.length());
//                msgBuffer.append("正在搜索设备...");
//                handler.sendEmptyMessage(7);
//                mScanner.startScan(new Scanner.onReceiveScannerListener() {
//                    @Override
//                    public void onReceiveScanDevice(BluetoothDevice device, int rssi, byte[] scanRecord) {
//                        if ( (scanRecord != null) && (StringTool.byteHexToSting(scanRecord).contains("017f5450"))) {  //从广播数据中过滤掉其它蓝牙设备
//                            msgBuffer.delete(0, msgBuffer.length());
//                            handler.sendEmptyMessage(7);
//                        }
//                    }
//                });
//            }
        }
    }

    //读卡按键监听
    private class SendButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if ((bleNfcDevice.isConnection() != BleManager.STATE_CONNECTED)) {
                msgText.setText("设备未连接，请先连接设备！");
                return;
            }
            //寻卡一次
            bleNfcDevice.requestRfmSearchCard(ComByteManager.ISO14443_P4);
        }
    }

    //修改蓝牙名称按键监听
    private class changeBleNameButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if ((bleNfcDevice.isConnection() != BleManager.STATE_CONNECTED)) {
                msgText.setText("设备未连接，请先连接设备！");
                return;
            }

            final EditText inputEditText = new EditText(MainbActivity.this);
            //inputEditText.setInputType(InputType.TYPE_CLASS_TEXT);
            //inputEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(16)});
            new AlertDialog.Builder(MainbActivity.this)
                    .setTitle("修改蓝牙名称")
                    .setMessage("请输入新名称")
                    .setIcon(android.R.drawable.ic_dialog_info)
                    .setView(inputEditText)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            final String bleName = inputEditText.getText().toString();
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        //开始验证
                                        if (bleNfcDevice.changeBleName(bleName)) {
                                            msgBuffer.delete(0, msgBuffer.length());
                                            msgBuffer.append("蓝牙名称修改成功！重启设备后生效。").append("\r\n");
                                            handler.sendEmptyMessage(0);
                                        } else {
                                            msgBuffer.delete(0, msgBuffer.length());
                                            msgBuffer.append("蓝牙名称修改失败！").append("\r\n");
                                            handler.sendEmptyMessage(0);
                                        }
                                    } catch (DeviceNoResponseException e) {
                                        e.printStackTrace();
                                        msgBuffer.delete(0, msgBuffer.length());
                                        msgBuffer.append("蓝牙名称修改失败！").append("\r\n");
                                        handler.sendEmptyMessage(0);
                                    }
                                }
                            }).start();
                        }
                    })
                    .setNegativeButton("取消", null)
                    .show();
        }
    }

    //清空显示按键监听
    private class claerButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            msgBuffer.delete(0, msgBuffer.length());
            handler.sendEmptyMessage(0);

//            byte[] sendBytes = new byte[]{
//                    0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99,
//                    0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99,
//                    0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99,
//                    0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99,
//                    0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99,
//                    0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99,
//                    0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99,
//                    0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99,
//                    0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99,
//                    0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99,
//                    0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99,
//                    0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99,
//                    0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99,
//                    0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99,
//                    0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99,
//                    0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99,
//                    0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99,
//                    0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99,
//                    0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99,
//                    0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99};
//            StringBuffer stringBuffer = new StringBuffer();
//            for (int i=0; i<sendBytes.length; i++) {
//                stringBuffer.append(String.format("%02x", sendBytes[i]));
//            }
//
//            final SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss.SSS");
//            Date curDate =  new Date(System.currentTimeMillis());
//            msgBuffer.append(String.format("发送时间：" + formatter.format(curDate) + "\r\n"));
//            msgBuffer.append(String.format("发送数据长度：%d\r\n", sendBytes.length));
//            msgBuffer.append("发送的数据：\r\n" + stringBuffer);
//            bleNfcDevice.requestPalTestChannel(sendBytes,
//                    new DeviceManager.onReceivePalTestChannelListener() {
//                        @Override
//                        public void onReceivePalTestChannel(byte[] returnData) {
//                            Date curDate =  new Date(System.currentTimeMillis());
//                            msgBuffer.append(String.format("\r\n发送完成！\r\n"));
//                            StringBuffer stringBuffer = new StringBuffer();
//                            for (int i=0; i<returnData.length; i++) {
//                                stringBuffer.append(String.format("%02x", returnData[i]));
//                            }
//                            System.out.println(stringBuffer);
//                            msgBuffer.append("开始接收数据：\r\n" + stringBuffer);
//                            msgBuffer.append(String.format("\r\n接收数据长度：%d\r\n", returnData.length));
//                            msgBuffer.append(String.format("结束时间：" + formatter.format(curDate) + "\r\n"));
//                            handler.sendEmptyMessage(0);
//                        }
//                    });
        }
    }

    //打开蜂鸣器监听
    private class OpenBeepButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if ((bleNfcDevice.isConnection() != BleManager.STATE_CONNECTED)) {
                msgText.setText("设备未连接，请先连接设备！");
                return;
            }
            bleNfcDevice.requestOpenBeep(50, 50, 255, new DeviceManager.onReceiveOpenBeepCmdListener() {
                @Override
                public void onReceiveOpenBeepCmd(boolean isSuc) {
                    if (isSuc) {
                        msgBuffer.delete(0, msgBuffer.length());
                        msgBuffer.append("打开蜂鸣器成功");
                        handler.sendEmptyMessage(0);
                    }
                }
            });
        }
    }

    //关闭蜂鸣器监听
    private class closeBeepButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if ((bleNfcDevice.isConnection() != BleManager.STATE_CONNECTED)) {
                msgText.setText("设备未连接，请先连接设备！");
                return;
            }
            bleNfcDevice.requestOpenBeep(50, 50, 0, new DeviceManager.onReceiveOpenBeepCmdListener() {
                @Override
                public void onReceiveOpenBeepCmd(boolean isSuc) {
                    if (isSuc) {
                        msgBuffer.delete(0, msgBuffer.length());
                        msgBuffer.append("关闭蜂鸣器成功");
                        handler.sendEmptyMessage(0);
                    }
                }
            });
        }
    }

    //打开防丢器功能监听
    private class OpenAntiLostButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if ((bleNfcDevice.isConnection() != BleManager.STATE_CONNECTED)) {
                msgText.setText("设备未连接，请先连接设备！");
                return;
            }
            bleNfcDevice.requestAntiLostSwitch(true, new DeviceManager.onReceiveAntiLostSwitchListener() {
                @Override
                public void onReceiveAntiLostSwitch(boolean isSuc) {
                    if (isSuc) {
                        msgBuffer.delete(0, msgBuffer.length());
                        msgBuffer.append("打开防丢器功能成功");
                        handler.sendEmptyMessage(0);
                    }
                }
            });
        }
    }

    //关闭防丢器功能监听
    private class CloseAntiLostButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if ((bleNfcDevice.isConnection() != BleManager.STATE_CONNECTED)) {
                msgText.setText("设备未连接，请先连接设备！");
                return;
            }
            bleNfcDevice.requestAntiLostSwitch(false, new DeviceManager.onReceiveAntiLostSwitchListener() {
                @Override
                public void onReceiveAntiLostSwitch(boolean isSuc) {
                    if (isSuc) {
                        msgBuffer.delete(0, msgBuffer.length());
                        msgBuffer.append("关闭防丢器功能成功");
                        handler.sendEmptyMessage(0);
                    }
                }
            });
        }
    }

    //打开自动寻卡按键监听
    private class OpenAutoSearchCardButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if ((bleNfcDevice.isConnection() != BleManager.STATE_CONNECTED)) {
                msgText.setText("设备未连接，请先连接设备！");
                return;
            }

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        //打开/关闭自动寻卡，200ms间隔，寻M1/UL卡
                        boolean isSuc = bleNfcDevice.startAutoSearchCard((byte) 20, ComByteManager.ISO14443_P4);
                        if (isSuc) {
                            msgBuffer.delete(0, msgBuffer.length());
                            msgBuffer.append("自动寻卡已打开！\r\n");
                            handler.sendEmptyMessage(0);
                        } else {
                            msgBuffer.delete(0, msgBuffer.length());
                            msgBuffer.append("自动寻卡已关闭！\r\n");
                            handler.sendEmptyMessage(0);
                        }
                    } catch (DeviceNoResponseException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

    //关闭自动寻卡按键监听
    private class CloseAutoSearchCardButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if ((bleNfcDevice.isConnection() != BleManager.STATE_CONNECTED)) {
                msgText.setText("设备未连接，请先连接设备！");
                return;
            }
            //打开/关闭自动寻卡，100ms间隔，寻M1/UL卡、CPU卡
            bleNfcDevice.requestRfmAutoSearchCard(false, (byte) 20, ComByteManager.ISO14443_P4, new DeviceManager.onReceiveAutoSearchCardListener() {
                @Override
                public void onReceiveAutoSearchCard(boolean isSuc) {
                    if (isSuc) {
                        msgBuffer.delete(0, msgBuffer.length());
                        msgBuffer.append("自动寻卡已打开！\r\n");
                        handler.sendEmptyMessage(0);
                    } else {
                        msgBuffer.delete(0, msgBuffer.length());
                        msgBuffer.append("自动寻卡已关闭！\r\n");
                        handler.sendEmptyMessage(0);
                    }
                }
            });
        }
    }

    //开始自动寻卡
    private void startAutoSearchCard() throws DeviceNoResponseException {
        //打开自动寻卡，200ms间隔，寻M1/UL卡
        boolean isSuc = bleNfcDevice.startAutoSearchCard((byte) 20, ComByteManager.ISO14443_P4);
        if (!isSuc) {
            //msgBuffer.delete(0, msgBuffer.length());
            msgBuffer.append("不支持自动寻卡！\r\n");
            handler.sendEmptyMessage(0);
        }
    }
    private void toNextActivity(String deviseid) {
        Intent intent = new Intent();
        if ("deviceadd".equals(shangye)) {
            intent.setClass(MainbActivity.this, DeviceaddAct.class);
            intent.putExtra("ID", deviseid);
            startActivity(intent);
            finish();
        }
        if ("XUNJIAN".equals(shangye)) {
            JobLBean.DataBean data = (JobLBean.DataBean) intent2.getSerializableExtra("jobbean");
            LogUtil.e("扫描得到的：", deviseid + "上页带来的：" + data.getDevId());
            if (deviseid.equals(data.getDevId())) {
                intent.setClass(MainbActivity.this, JobCheckActivity.class);
                intent.putExtra("jobbean", data);
                startActivity(intent);
                finish();
            } else {
                Looper.prepare();
                ToastUtils.show(MainbActivity.this, "该设备不是作业目标设备");

                intent.setClass(MainbActivity.this, Job_LActivity.class);
                intent.putExtra("taskId", data.getTaskId());
                startActivity(intent);
                finish();
                Looper.loop();
            }
        }
        if ("F_XUNJIAN".equals(shangye)) {
            taskId = intent2.getIntExtra("taskId", -1);//deviseid
            initDvData(taskId,deviseid);
        }
        if ("WEIXIU".equals(shangye)) {
            FaultJobLBean.DataBean data = (FaultJobLBean.DataBean) intent2.getSerializableExtra("jobbean");
            LogUtil.e("扫描得到的：", deviseid + "上页带来的：" + data.getDevId());
            if (deviseid.equals(data.getDevId())) {
                intent.setClass(MainbActivity.this, FaultJobSubmitActivity.class);
                intent.putExtra("jobbean", data);
                startActivity(intent);
                finish();
            } else {
                Looper.prepare();
                ToastUtils.show(this, "该设备不是作业目标设备");
                intent.setClass(MainbActivity.this, FaultJob_LActivity.class);
                startActivity(intent);
                finish();
                Looper.loop();
            }
        }

        if ("tietakankan".equals(shangye)) {
            intent.setClass(MainbActivity.this, Device_XActivity.class);
            intent.putExtra("deviceId", deviseid);
            startActivity(intent);
            finish();
        }
    }
    //读写卡Demo
    private boolean readWriteCardDemo(int cardType) {
        switch (cardType) {
            case DeviceManager.CARD_TYPE_ISO4443_B:  //寻到 B cpu卡
                final Iso14443bCard iso14443bCard = (Iso14443bCard) bleNfcDevice.getCard();
                if (iso14443bCard != null) {
                    msgBuffer.delete(0, msgBuffer.length());
                    msgBuffer.append("寻到ISO14443-B卡->UID:(身份证发送0036000008指令获取UID)\r\n");
                    handler.sendEmptyMessage(0);
                    //获取身份证DN码的指令流
                    final byte[][] sfzCmdBytes = {
                            {0x00, (byte) 0xa4, 0x00, 0x00, 0x02, 0x60, 0x02},
                            {0x00, 0x36, 0x00, 0x00, 0x08},
                            {(byte) 0x80, (byte) 0xB0, 0x00, 0x00, 0x20},
                    };
                    System.out.println("发送指令流");
                    for (byte[] aBytes : sfzCmdBytes) {
                        try {
                            msgBuffer.append("发送：").append(StringTool.byteHexToSting(aBytes)).append("\r\n");
                            handler.sendEmptyMessage(0);
                            byte returnBytes[] = iso14443bCard.transceive(aBytes);
                            msgBuffer.append("返回：").append(StringTool.byteHexToSting(returnBytes)).append("\r\n");
                            handler.sendEmptyMessage(0);
                        } catch (CardNoResponseException e) {
                            e.printStackTrace();
                            return false;
                        }
                    }
                }
                break;
            case DeviceManager.CARD_TYPE_ISO4443_A:   //寻到A CPU卡
                final CpuCard cpuCard = (CpuCard) bleNfcDevice.getCard();
                if (cpuCard != null) {
                    msgBuffer.delete(0, msgBuffer.length());
                    msgBuffer.append("寻到CPU卡->UID:").append(cpuCard.uidToString()).append("\r\n");
                    handler.sendEmptyMessage(0);
                    try {
                        //选择深圳通主文件
                        byte[] bytApduRtnData = cpuCard.transceive(SZTCard.getSelectMainFileCmdByte());
                        if (bytApduRtnData.length <= 2) {
                            System.out.println("不是深圳通卡，当成银行卡处理！");
                            //选择储蓄卡交易文件
                            String cpuCardType;
                            bytApduRtnData = cpuCard.transceive(FinancialCard.getSelectDepositCardPayFileCmdBytes());
                            if (bytApduRtnData.length <= 2) {
                                System.out.println("不是储蓄卡，当成借记卡处理！");
                                //选择借记卡交易文件
                                bytApduRtnData = cpuCard.transceive(FinancialCard.getSelectDebitCardPayFileCmdBytes());
                                if (bytApduRtnData.length <= 2) {
                                    msgBuffer.append("未知CPU卡！");
                                    handler.sendEmptyMessage(0);
                                    return false;
                                } else {
                                    cpuCardType = "储蓄卡";
                                }
                            } else {
                                cpuCardType = "借记卡";
                            }

                            //发送获取银行卡卡号指令
                            bytApduRtnData = cpuCard.transceive(FinancialCard.getCardNumberCmdBytes());
                            //提取银行卡卡号
                            String cardNumberString = FinancialCard.extractCardNumberFromeRturnBytes(bytApduRtnData);
                            if (cardNumberString == null) {
                                msgBuffer.append("未知CPU卡！");
                                handler.sendEmptyMessage(0);
                                return false;
                            } else {
                                msgBuffer.append(cpuCardType).append("卡号：").append(cardNumberString);
                                handler.sendEmptyMessage(0);

                                //读交易记录
                                System.out.println("发送APDU指令-读10条交易记录");
                                for (int i = 1; i <= 10; i++) {
                                    bytApduRtnData = cpuCard.transceive(FinancialCard.getTradingRecordCmdBytes((byte) i));
                                    msgBuffer.append(FinancialCard.extractTradingRecordFromeRturnBytes(bytApduRtnData));
                                    handler.sendEmptyMessage(0);
                                }
                            }
                        } else {  //深圳通处理流程
                            bytApduRtnData = cpuCard.transceive(SZTCard.getBalanceCmdByte());
                            if (SZTCard.getBalance(bytApduRtnData) == null) {
                                msgBuffer.append("未知CPU卡！");
                                handler.sendEmptyMessage(0);
                                System.out.println("未知CPU卡！");
                                return false;
                            } else {
                                msgBuffer.append("深圳通余额：").append(SZTCard.getBalance(bytApduRtnData));
                                handler.sendEmptyMessage(0);
                                System.out.println("余额：" + SZTCard.getBalance(bytApduRtnData));
                                //读交易记录
                                System.out.println("发送APDU指令-读10条交易记录");
                                for (int i = 1; i <= 10; i++) {
                                    bytApduRtnData = cpuCard.transceive(SZTCard.getTradeCmdByte((byte) i));
                                    msgBuffer.append("\r\n").append(SZTCard.getTrade(bytApduRtnData));
                                    handler.sendEmptyMessage(0);
                                }
                            }
                        }
                    } catch (CardNoResponseException e) {
                        e.printStackTrace();
                        return false;
                    }
                }
                break;
            case DeviceManager.CARD_TYPE_FELICA:  //寻到FeliCa
                FeliCa feliCa = (FeliCa) bleNfcDevice.getCard();
                if (feliCa != null) {
                    msgBuffer.delete(0, msgBuffer.length());
                    msgBuffer.append("读取服务008b中数据块0000的数据：\r\n");
                    handler.sendEmptyMessage(0);
                    byte[] pServiceList = {(byte) 0x8b, 0x00};
                    byte[] pBlockList = {0x00, 0x00, 0x00};
                    try {
                        byte[] pBlockData = feliCa.read((byte) 1, pServiceList, (byte) 1, pBlockList);
                        msgBuffer.append(StringTool.byteHexToSting(pBlockData)).append("\r\n");
                        handler.sendEmptyMessage(0);
                    } catch (CardNoResponseException e) {
                        e.printStackTrace();
                        return false;
                    }
                }
                break;
            case DeviceManager.CARD_TYPE_ULTRALIGHT: //寻到Ultralight卡
                String writeText = System.currentTimeMillis() + "中科消防！";
                if (msgText.getText().toString().length() > 0) {
                    writeText = msgText.getText().toString();
                }

                final Ntag21x ntag21x = (Ntag21x) bleNfcDevice.getCard();
                if (ntag21x != null) {
                    msgBuffer.delete(0, msgBuffer.length());
                    BigInteger srch = new BigInteger(ntag21x.uidToString(), 16);
                    msgBuffer.append("寻到Ultralight卡 ->UID:").append(srch.toString()).append("\r\n");


                    final String deviseid = srch.toString();
//

                    toNextActivity(deviseid);
                    //new My().execute();
//                    Map<String, String> map = new HashMap<>();
//                    map.put("id", deviseid);
//                    map.put("s5", "3");
//
//                    String s = map.toString();
//                    Log.e("map===", s);
//
//                    int i = GetNetype(getApplicationContext());
//                    Log.e("i===", i + "");
//                    if (i == -1) {
//                        Intent intent1 = new Intent();
//                        intent1.putExtra("ID", id + "");//
//
//                        if ("shebeitianjia".equals(shangye)) {
//                            intent1.putExtra("wangluo", "wu");
//                            intent1.putExtra("tag", "saomiao");
//                            intent1.setClass(MainbActivity.this, Activity_shebeiAdd.class);
//                            startActivity(intent1);
//                        } else if ("xunjianJob".equals(shangye)) {
//                            intent1.putExtra("id", id + "");
//                            intent1.setClass(MainbActivity.this, MyJinjob.class);
//                            startActivity(intent1);
//                            finish();
//                        } else if ("tietakankan".equals(shangye)) {
//                            intent1.putExtra("tag", "tietakankan");
//                            intent1.putExtra("ID", id);
//                            intent1.setClass(MainbActivity.this, DeviceActivity.class);
//                            startActivity(intent1);
//                            finish();
//                        } else {
//                              if ((id + "").equals(id_old)) {
//
//                                Log.e("" + id, "----" + id_old);
//                             // if (true) {
//                                if (form.equals("weibao")) {
//                                    intent1.setClass(MainbActivity.this, Checkweibao_activity.class);
//                                } else if (form.equals("xunjian")) {
//                                    intent1.setClass(MainbActivity.this, CheckActivity.class);
//                                }else if (form.equals("bendixunjian")){
//                                    intent1.setClass(MainbActivity.this, CheckActivity.class);
//                                    intent1.putExtra("neirong",neirong);
//                                    intent1.putExtra("shebeiMingcheng",shebeiMingcheng);
//                                }
//                                intent1.putExtra("wangluo", "wu");
//                                intent1.putExtra("ID", "" + id_old);
//                                intent1.putExtra("pollingId", "" + pollingId);
//                                startActivity(intent1);
//                                finish();
//                            } else {
//                                Toast.makeText(MainbActivity.this, "此设备不是该任务对应的设备", Toast.LENGTH_SHORT).show();
//                                finish();
//                            }
//                        }
//                        finish();
//                    } else {
//                        OkHttpUtils.post().url(ConstantsXF.URL_IscunZai).params(map).build().execute(new StringCallback() {
//                            @Override
//                            public void onError(Call call, Exception e, int i) {
//                                Log.e("连接失败", "网络链接失败了" + e.getMessage());
//                            }
//
//                            @Override
//                            public void onResponse(String s, int i) {
//                                try {
//                                    JSONObject jsonObject = new JSONObject(s);
//                                    int status = (int) jsonObject.get("status");
//                                    String info = (String) jsonObject.get("info");
//                                    Intent intent1 = new Intent();
//                                    intent1.putExtra("ID", id + "");
//                                    Log.i("======", "s: " + s);
//
//
//                                    if ("shebeitianjia".equals(shangye)) {
//                                        if (1 == status) {
//                                            intent1.putExtra("wangluo", "you");
//                                            intent1.putExtra("tag", "saomiao");
//                                            intent1.setClass(MainbActivity.this, Activity_shebeiAdd.class);
//                                            startActivity(intent1);
//                                        } else {
//                                            Toast.makeText(getApplicationContext(), "该设备信息已经存在，不可重复添加", Toast.LENGTH_SHORT).show();
//
//                                        }
//                                        finish();
//
//                                    } else if ("xunjianJob".equals(shangye)) {
//                                    getData2(deviseid);
//                                    } else if ("tietakankan".equals(shangye)) {
//                                        intent1.putExtra("tag", "tietakankan");
//                                        intent1.putExtra("ID", id);
//                                        intent1.setClass(MainbActivity.this, DeviceActivity.class);
//                                        startActivity(intent1);
//                                        finish();
//                                    } else {
//                                        if ((id + "").equals(id_old)) {
//
//                                        Log.e("" + id, "----" + id_old);
//                                            //if (true) {
//                                            if (form.equals("weibao")) {
//                                                intent1.setClass(MainbActivity.this, Checkweibao_activity.class);
//                                            } else if (form.equals("xunjian")) {
//                                                intent1.setClass(MainbActivity.this, CheckActivity.class);
//                                            }else if (form.equals("bendixunjian")){
//                                                intent1.setClass(MainbActivity.this, CheckActivity.class);
//                                                intent1.putExtra("neirong",neirong);
//                                                intent1.putExtra("shebeiMingcheng",shebeiMingcheng);
//                                            }
//                                            intent1.putExtra("wangluo", "you");
//                                            intent1.putExtra("ID", "" + id_old);
//                                            intent1.putExtra("pollingId", "" + pollingId);
//                                            startActivity(intent1);
//                                            finish();
//                                        } else {
//                                            Toast.makeText(MainbActivity.this, "此设备不是该任务对应的设备", Toast.LENGTH_SHORT).show();
//                                            finish();
//                                        }
//                                    }
//
//                                } catch (JSONException e) {
//
//
//                                }
//                            }
//                        });
//                    }


                    handler.sendEmptyMessage(0);

                }
                break;
            case DeviceManager.CARD_TYPE_MIFARE:   //寻到Mifare卡
                final Mifare mifare = (Mifare) bleNfcDevice.getCard();
                if (mifare != null) {
                    msgBuffer.delete(0, msgBuffer.length());
                    msgBuffer.append("寻到Mifare卡->UID:").append(mifare.uidToString()).append("\r\n");
                    msgBuffer.append("开始验证第1块密码\r\n");
                    handler.sendEmptyMessage(0);
                    byte[] key = {(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff};
                    try {
                        boolean anth = mifare.authenticate((byte) 1, Mifare.MIFARE_KEY_TYPE_A, key);
                        if (anth) {
                            msgBuffer.append("验证密码成功\r\n");
                            msgBuffer.append("写00112233445566778899001122334455到块1\r\n");
                            handler.sendEmptyMessage(0);
                            boolean isSuc = mifare.write((byte) 1, new byte[]{0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88, (byte) 0x99, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55});
                            if (isSuc) {
                                msgBuffer.append("写成功！\r\n");
                                msgBuffer.append("读块1数据\r\n");
                                handler.sendEmptyMessage(0);
                                byte[] readDataBytes = mifare.read((byte) 1);
                                msgBuffer.append("块1数据:").append(StringTool.byteHexToSting(readDataBytes)).append("\r\n");
                                handler.sendEmptyMessage(0);
                            } else {
                                msgBuffer.append("写失败！\r\n");
                                handler.sendEmptyMessage(0);
                                return false;
                            }
                        } else {
                            msgBuffer.append("验证密码失败\r\n");
                            handler.sendEmptyMessage(0);
                            return false;
                        }
                    } catch (CardNoResponseException e) {
                        e.printStackTrace();
                        return false;
                    }
                }
                break;
            case DeviceManager.CARD_TYPE_ISO15693: //寻到15693卡
                final Iso15693Card iso15693Card = (Iso15693Card) bleNfcDevice.getCard();
                if (iso15693Card != null) {
                    msgBuffer.delete(0, msgBuffer.length());
                    msgBuffer.append("寻到15693卡->UID:").append(iso15693Card.uidToString()).append("\r\n");
                    msgBuffer.append("读块0数据\r\n");
                    handler.sendEmptyMessage(0);
                    try {
                        msgBuffer.append("写数据01020304到块4").append("\r\n");
                        handler.sendEmptyMessage(0);
                        boolean isSuc = iso15693Card.write((byte) 4, new byte[]{0x01, 0x02, 0x03, 0x04});
                        if (isSuc) {
                            msgBuffer.append("写数据成功！").append("\r\n");
                            handler.sendEmptyMessage(0);
                        } else {
                            msgBuffer.append("写数据失败！").append("\r\n");
                            handler.sendEmptyMessage(0);
                        }
                        msgBuffer.append("读块4数据").append("\r\n");
                        handler.sendEmptyMessage(0);
                        byte[] bytes = iso15693Card.read((byte) 4);
                        msgBuffer.append("块4数据：").append(StringTool.byteHexToSting(bytes)).append("\r\n");
                        handler.sendEmptyMessage(0);
                    } catch (CardNoResponseException e) {
                        e.printStackTrace();
                        return false;
                    }
                }
                break;
        }
        return true;
    }
//    private void getData2(final String deviceid) {
//        Map map = new HashMap();
//        map.put("s5", "1");
//        map.put("deviceId", deviceid);
//        OkHttpUtils.post().url(ConstantsXF.URL_GETDEVICEBYID).params(map).build().execute(new StringCallback() {
//            @Override
//            public void onError(Call call, Exception e, int i) {
//                Log.e("请求失败", "请求失败了" + e.getMessage());
//            }
//
//            @Override
//            public void onResponse(String s, int i) {
//                Log.e("请求成功了", "这是请求得到的数据" + s);
//                try {
//                    Gson gson = new Gson();
//                    Device_Li device_li = gson.fromJson(s, Device_Li.class);
//                    Device_Li.DataBean data = device_li.getData();
//                    if (data != null) {
//                       id2 = data.getId();
//                        String deviceNumber = data.getDeviceNumber();
//                        String position = data.getPosition();
//                        Map<String, String> map = new HashMap<>();
//                        map.put("userId", UserID.USERID);
//                        map.put("s5", "1");
//                        map.put("deviceId", id2);
//                        if (dijige.equals("0")){
//                            map.put("taskStatus", "1");
//                        }else {
//                            map.put("taskStatus", "2");
//                        }
//
//                        Log.e("入参是：",map.toString()+"<>");
//                        OkHttpUtils.post().url(ConstantsXF.URL_CheckJob_Li).params(map).build().execute(new StringCallback() {
//                            @Override
//                            public void onError(Call call, Exception e, int i) {
//                                Log.e("9090", e + "");
//                            }
//
//                            @Override
//                            public void onResponse(String s, int i) {
//                                CheckJobData_Li checkJobData_li = new Gson().fromJson(s, CheckJobData_Li.class);
//                                //得到巡检任务集合
//                                Log.e("该巡点的进行中任务数据=", s);
//                                List<CheckJobData_Li.DataBean> data = checkJobData_li.getData();
//                                if (data.size() > 0) {
//
//                                    if ("0".equals(dijige)){
//                                        Intent intent1=new Intent(MainbActivity.this,CheckActivity.class);
//                                        intent1.putExtra("wangluo", "you");
//                                        intent1.putExtra("ID", "" + deviceid);
//                                        intent1.putExtra("pollingId", "" + data.get(0).getId());
//                                        startActivity(intent1);
//                                    }else {
//                                        Intent intent1=new Intent(MainbActivity.this,YilouJob.class);
//                                        intent1.putExtra("deviceid",id2);
//                                        startActivity(intent1);
//                                    }
//
//                                    finish();
////                                    lin_job.setVisibility(View.VISIBLE);
////                                    CheckJobData_Li.DataBean dataBean = data.get(0);
////                                    pollingId = dataBean.getId();
////                                    tvAddress.setText("" + position);
////                                    tvId.setText("设备ID     ：" + deviceid);
////                                    tvName.setText("设备名称：" + deviceNumber);
////                                    tvNumber.setText("巡检任务号：" + pollingId);
////                                    Log.e("新数据的长度=", data.size() + "");
////                                    Intent intent = new Intent(MyJinjob.this, DeviceActivity.class);
////                                    intent.putExtra("pollingId", pollingId);
////                                    intent.putExtra("ID", deviceid + "");
////                                    intent.putExtra("tag", "myjob");
////                                    startActivity(intent);
////                                    finish();
//
//                                } else {
//                                    Toast.makeText(MainbActivity.this, "该设备暂无对应的巡检任务", Toast.LENGTH_SHORT).show();
//                                }
//
//                            }
//                        });//设备ID
//                    } else {
//                        finish();
//                        Toast.makeText(MainbActivity.this, "该设备基本信息尚未采集", Toast.LENGTH_SHORT).show();
//                    }
//
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//
//        });
//
//    }
    //返回值 -1：没有网络  1：WIFI网络2：wap网络3：net网络  
    public static int GetNetype(Context context) {
        int netType = -1;
        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo == null) {
            return netType;
        }
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_MOBILE) {
            if (networkInfo.getExtraInfo().toLowerCase().equals("cmnet")) {
                netType = 3;
            } else {
                netType = 2;
            }
        } else if (nType == ConnectivityManager.TYPE_WIFI) {
            netType = 1;
        }
        return netType;
    }

    //搜索最近的设备并连接
    private void searchNearestBleDevice() {
        msgBuffer.delete(0, msgBuffer.length());
        msgBuffer.append("正在搜索设备...");
        handler.sendEmptyMessage(0);
        if (!mScanner.isScanning() && (bleNfcDevice.isConnection() == BleManager.STATE_DISCONNECTED)) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    synchronized (this) {
                        mScanner.startScan(0);
                        mNearestBleLock.lock();
                        try {
                            mNearestBle = null;
                        } finally {
                            mNearestBleLock.unlock();
                        }
                        lastRssi = -100;

                        int searchCnt = 0;
                        while ((mNearestBle == null)
                                && (searchCnt < 10000)
                                && (mScanner.isScanning())
                                && (bleNfcDevice.isConnection() == BleManager.STATE_DISCONNECTED)) {
                            searchCnt++;
                            try {
                                Thread.sleep(1);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }

                        if (mScanner.isScanning() && (bleNfcDevice.isConnection() == BleManager.STATE_DISCONNECTED)) {
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            mScanner.stopScan();
                            mNearestBleLock.lock();
                            try {
                                if (mNearestBle != null) {
                                    mScanner.stopScan();
                                    msgBuffer.delete(0, msgBuffer.length());
                                    msgBuffer.append("正在连接设备...");
                                    handler.sendEmptyMessage(0);
                                    bleNfcDevice.requestConnectBleDevice(mNearestBle.getAddress());
                                } else {
                                    msgBuffer.delete(0, msgBuffer.length());
                                    msgBuffer.append("未找到设备！");
                                    handler.sendEmptyMessage(0);
                                }
                            } finally {
                                mNearestBleLock.unlock();
                            }
                        } else {
                            mScanner.stopScan();
                        }
                    }
                }
            }).start();
        }
    }

    //发送读写进度条显示Handler
    private void showReadWriteDialog(String msg, int rate) {
        Message message = new Message();
        message.what = 4;
        message.arg1 = rate;
        message.obj = msg;
        handler.sendMessage(message);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            msgText.setText(msgBuffer);

            if ((bleNfcDevice.isConnection() == BleManager.STATE_CONNECTED) || ((bleNfcDevice.isConnection() == BleManager.STATE_CONNECTING))) {
                searchButton.setText("断开连接");
            } else {
                searchButton.setText("搜索蓝牙设备");
            }

            switch (msg.what) {
                case 1:
                    break;
                case 2:
                    break;
                case 3:
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                byte versions = bleNfcDevice.getDeviceVersions();
                                msgBuffer.append("设备版本:").append(String.format("%02x", versions)).append("\r\n");
                                handler.sendEmptyMessage(0);
                                double voltage = bleNfcDevice.getDeviceBatteryVoltage();
                                msgBuffer.append("设备电池电压:").append(String.format("%.2f", voltage)).append("\r\n");
                                if (voltage < 3.61) {
                                    msgBuffer.append("设备电池电量低，请及时充电！");
                                } else {
                                    msgBuffer.append("设备电池电量充足！");
                                }
                                handler.sendEmptyMessage(0);
                                boolean isSuc = bleNfcDevice.androidFastParams(true);
                                if (isSuc) {
                                    msgBuffer.append("\r\n蓝牙快速传输参数设置成功!");
                                } else {
                                    msgBuffer.append("\n不支持快速传输参数设置!");
                                }
                                handler.sendEmptyMessage(0);

                                msgBuffer.append("\n开启自动寻卡...\r\n");
                                handler.sendEmptyMessage(0);
                                //开始自动寻卡
                                startAutoSearchCard();
                            } catch (DeviceNoResponseException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                    break;

                case 4:   //读写进度条
                    if ((msg.arg1 == 0) || (msg.arg1 == 100)) {
                        readWriteDialog.dismiss();
                        readWriteDialog.setProgress(0);
                    } else {
                        readWriteDialog.setMessage((String) msg.obj);
                        readWriteDialog.setProgress(msg.arg1);
                        if (!readWriteDialog.isShowing()) {
                            readWriteDialog.show();
                        }
                    }
                    break;
                case 7:  //搜索设备列表
                    items = mScanner.getDeviceNames();
                    if (alertDialog == null) {
                        alertDialog = new AlertDialog.Builder(MainbActivity.this)
                                .setTitle("请选择设备连接")
                                .setItems(items, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        // TODO Auto-generated method stub
                                        mScanner.stopScan();
                                        mScanner.setOnReceiveScannerListener(null);
                                        msgBuffer.delete(0, msgBuffer.length());
                                        msgBuffer.append("正在连接设备...");
                                        handler.sendEmptyMessage(0);
                                        bleNfcDevice.requestConnectBleDevice(mScanner.getDeviceList().get(which).getAddress());
                                    }
                                })
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        mScanner.stopScan();
                                        mScanner.setOnReceiveScannerListener(null);
                                    }
                                });
                        alertDialog.show();
                    }
//                    else if (!alertDialog.create().isShowing()) {
//                        alertDialog.show();
//                    }
                    else {
                        alertDialog.setItems(items, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // TODO Auto-generated method stub
                                mScanner.stopScan();
                                mScanner.setOnReceiveScannerListener(null);
                                msgBuffer.delete(0, msgBuffer.length());
                                msgBuffer.append("正在连接设备...");
                                handler.sendEmptyMessage(0);
                                bleNfcDevice.requestConnectBleDevice(mScanner.getDeviceList().get(which).getAddress());
                            }
                        });
                        alertDialog.create().show();
                    }
                    break;
            }
        }
    };



    //验证作业是否存在

    private void initDvData( int taskId,String deviseid) {
        Map map = new HashMap<String, Object>();
        map.put("taskId", taskId);
        map.put("jobResult", 0 + "");
        map.put("devId", deviseid + "");
        requestInspect = new RequestInspect();
        requestInspect.setPageNum(1);
        requestInspect.setPageSize(1);
        requestInspect.setParam(map);
        requestInspect.setAccessId(SPUtil.getString(this, Constants_SP.ACCESSID));
        requestInspect.setAction(4);
        requestInspect.setTimeStamp(TimeUtils.getTime());
        requestInspect.setSign(MyApplication.getInstance().generateDvSign(requestInspect));
        jobLPresenter.getJobL(requestInspect);
    }

}
